package com.woniu.controller;

import com.woniu.entity.User;
import com.woniu.service.UserService;
import com.woniu.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin("*")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService service;

    @RequestMapping("/save")
    public ResultVO<User> save(@RequestBody User user) {
        ResultVO<User> vo = null;
        try {
            service.save(user);
            vo = new ResultVO<>(200,"增加成功", user);
        } catch (Exception e) {
            vo = new ResultVO<>(500,"增加失败");
            e.printStackTrace();
        }
        return vo;
    }

    @RequestMapping("/delete/{id}")
    public ResultVO delete(@PathVariable Integer id) {
        ResultVO<User> vo = null;
        try {
            service.delete(id);
            vo = new ResultVO<>(200,"删除成功");
        } catch (Exception e) {
            vo = new ResultVO<>(500,"删除失败");
            e.printStackTrace();
        }
        return vo;
    }

    @RequestMapping("/update")
    public ResultVO<User> update(@RequestBody User user) {
        ResultVO<User> vo = null;
        try {
            service.update(user);
            vo = new ResultVO<>(200,"修改成功",user);
        } catch (Exception e) {
            vo = new ResultVO<>(500,"修改失败");
            e.printStackTrace();
        }
        return vo;
    }

    @RequestMapping("/find/{id}")
    public ResultVO<User> findOne(@PathVariable Integer id) {
        ResultVO<User> vo = null;
        try {
            User user = service.findOne(id);
            vo = new ResultVO<>(200,"查询一个成功",user);
        } catch (Exception e) {
            vo = new ResultVO<>(500,"查询一个失败");
            e.printStackTrace();
        }
        return vo;
    }

    @RequestMapping("/find")
    public ResultVO<List<User>> findAll() {
        System.out.println("UserController.findAll");
        ResultVO<List<User>> vo = null;
        try {
            List<User> list = service.findAll();
            vo = new ResultVO<>(200,"查询成功",list);
        } catch (Exception e) {
            vo = new ResultVO<>(500,"查询失败");
            e.printStackTrace();
        }
        return vo;
    }
}
